package com.miracle.controller;
import com.miracle.common.response.HttpResult;
import com.miracle.common.response.ResultCodeEnum;
import com.miracle.entity.User;
import com.miracle.exception.UnauthorizedException;
import com.miracle.service.UserService;
import com.miracle.util.JWTUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

/*
 * 登录Controller
 * @author jie.xi
 * @date 2022/4/21 14:25
 */
@RestController
@RequestMapping("/user")
public class WebController {

    @Autowired
    UserService userService;

    @PostMapping("/login")
    public HttpResult login(@RequestParam("username") String username,
                            @RequestParam("password") String password) {
        System.out.println("=========开始登录============");
        User user = userService.getUser(username);
        if (user.getPassword().equals(password)) {
            return HttpResult.success(JWTUtil.sign(username,password));
        } else {
            throw new UnauthorizedException();
        }
    }

    @GetMapping("/test")
    public HttpResult article() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return HttpResult.success("你已经成功登录");
        } else {
            return HttpResult.failure(ResultCodeEnum.USER_WRONG);
        }
    }

    @GetMapping("/require_role")
    @RequiresRoles("admin")
    public HttpResult requireRole() {
        return HttpResult.success("你已经成功登录");
    }

    @RequestMapping("logout")
    public HttpResult logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return HttpResult.success("退出成功");
    }

    @RequestMapping(path = "/401")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public HttpResult unauthorized() {
        return HttpResult.failure(ResultCodeEnum.USER_LOGIN_AGAIN);
    }
}